package common

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"log"
	"math/rand"
	"time"
)

const (
	randBytes = `1234567890abcdefghijklmnopqrstuvwxyz`
	AES128    = 16
	AES192    = 24
	AES256    = 32

	AES_SIZE     = AES128
	RSA_KEY_SIZE = 1024
)

// 创建一个AES密钥
func CreateAesKey() []byte {
	key := make([]byte, AES_SIZE)
	rand.Seed(time.Now().Unix())
	for i := 0; i < AES_SIZE; i++ {
		key[i] = randBytes[rand.Intn(AES_SIZE)]
	}
	return key
}

// AES加密
func AesEncrypt(origData, key []byte) ([]byte, error) {
	defer func() {
		err := recover()
		if err != nil {
			log.Println(string(origData), string(key), "encrypt failed:", err)
		}
	}()

	// 分组秘钥
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	// 获取秘钥块的长度
	blockSize := block.BlockSize()
	// 补全码
	origData = PKCS7Padding(origData, blockSize)
	// 加密模式
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	// 创建数组
	crypted := make([]byte, len(origData))
	// 加密放入到创建的数组中
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

// AES解密
func AesDecrypt(crypted, key []byte) ([]byte, error) {
	defer func() {
		err := recover()
		if err != nil {
			log.Println(string(crypted), string(key), "decrypt failed:", err)
		}
	}()

	// 分组秘钥
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	// 获取秘钥块的长度
	blockSize := block.BlockSize()
	// 加密模式
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	// 创建数组
	origData := make([]byte, len(crypted))
	// 解密
	blockMode.CryptBlocks(origData, crypted)
	// 去补全码
	origData = PKCS7UnPadding(origData)
	return origData, nil
}

// 补齐空白，使其为密钥块长度(16)的整数倍，填充的内容为填充的长度
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding) // 填充
	return append(ciphertext, padtext...)
}

// 去除补齐的内容
func PKCS7UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
